package com.alibaba.citrus.cr.platform.enhance.facade.service.scitem;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.util.PageUtils;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.EmployeeGetCurrentLoginResponse;
import com.epoch.app.bcorder.model.dto.GetLoginEmployeeInfoResponse;
import com.epoch.app.bcorder.model.dto.OrganizationSDO;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.BcOrderService;
import com.epoch.app.crplatformenhance.enums.OrganizationTypeEnum;
import com.epoch.app.crplatformenhance.model.dto.GetTopOrganizationListRequest;
import com.epoch.app.crplatformenhance.model.dto.ScItemManageRangeLoadListRequest;
import com.epoch.app.crplatformenhance.model.dto.ScItemManageRangeQueryListRequest;
import com.epoch.app.crplatformenhance.model.dto.ScItemManageRangeSDO;
import com.epoch.app.crplatformenhance.model.dto.ScItemManageRangeSearchRequest;
import com.epoch.app.crplatformenhance.model.dto.StatusDesc;
import com.epoch.app.crplatformenhance.model.dto.TopOrganizationListResponse;
import com.epoch.app.crplatformenhance.model.enums.ScItemManageRangeStatus;
import com.epoch.app.crplatformenhance.scitemmanagerange.dto.QueryListRequest;
import com.epoch.app.crplatformenhance.scitemmanagerange.model.ScItemManageRange;
import com.epoch.app.crplatformenhance.scitemmanagerange.service.ScItemManageRangeService;
import com.epoch.app.crplatformenhance.scitemmanagerangeread.service.ScItemManageRangeReadService;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @description: 分子公司货品经营范围读取服务
 * @author: yuhw
 * @date: 2023年04月28日 17:32
 **/
@Component
@Primary
public class ScItemManageRangeReadServiceImpl implements ScItemManageRangeReadService {
    private static Log log = Log.getLogger(ScItemManageRangeReadServiceImpl.class);
    @Resource
    private ScItemManageRangeService scItemManageRangeService;
    @Resource
    private BaseDataService baseDataService;
    @Resource
    private CrPlatformEnhanceService crPlatformEnhanceService;
    @Resource
    private BcOrderService bcOrderService;

    private static final Integer MAX_PAGE_SIZE = 1000;

    /**
     * 货品范围列表查询
     * @param scItemManageRangeQueryListRequest
     * @return
     */
    @Override
    public Result<List<ScItemManageRangeSDO>> queryList(ScItemManageRangeQueryListRequest scItemManageRangeQueryListRequest) {
        //获取当前登录人的权限
        GetLoginEmployeeInfoResponse loginEmployeeInfo = baseDataService.getLoginEmployeeInfo();
        if (loginEmployeeInfo == null || loginEmployeeInfo.getOrganizationSDO() == null
            || loginEmployeeInfo.getOrganizationSDO().getId() == null
            || loginEmployeeInfo.getOrganizationSDO().getType() ==null){
            Result.success(null);
        }
        OrganizationSDO organizationSDO = loginEmployeeInfo.getOrganizationSDO();
        Integer orgType = organizationSDO.getType();
        String orgId = organizationSDO.getId();
        QueryListRequest queryListRequest = new QueryListRequest();
        //分子公司之上 可以看所有的销售组织
        if (orgType < OrganizationTypeEnum.COMPANY.getCode()){
            if (StringUtils.isNotBlank(scItemManageRangeQueryListRequest.getSaleOrgId())){
                queryListRequest.setSaleOrgId(scItemManageRangeQueryListRequest.getSaleOrgId());
            }
        }else if (OrganizationTypeEnum.COMPANY.getCode().equals(orgType)){
            //分子公司的限制分子公司层级
            queryListRequest.setBizUnitId(orgId);
            queryListRequest.setSaleOrgId(scItemManageRangeQueryListRequest.getSaleOrgId());
        }else if (OrganizationTypeEnum.SALES_ORGANIZATION.getCode().equals(orgType)){
            //销售组织层级限制到自身的销售组织
            queryListRequest.setSaleOrgId(orgId);
        }else {
            //销售组织下的渠道/部门 取到自己的销售组织层级
            TopOrganizationListResponse topOrganizationListResponse = queryTopSaleOrg(orgId);
            if (topOrganizationListResponse == null){
                return Result.success(null);
            }
            queryListRequest.setSaleOrgId(topOrganizationListResponse.getId());
        }
        //查询条件
        queryListRequest.setStart(scItemManageRangeQueryListRequest.getStart());
        queryListRequest.setLimit(scItemManageRangeQueryListRequest.getLimit());
        if (CollectionUtils.isNotEmpty(scItemManageRangeQueryListRequest.getScItemCodeList())){
            queryListRequest.setScItemCodes(scItemManageRangeQueryListRequest.getScItemCodeList());
        }
        if (StringUtils.isNotBlank(scItemManageRangeQueryListRequest.getScItemId())){
            queryListRequest.setScItemId(scItemManageRangeQueryListRequest.getScItemId());
        }
        if (scItemManageRangeQueryListRequest.getStatus() != null){
            queryListRequest.setStatus(scItemManageRangeQueryListRequest.getStatus());
        }
        queryListRequest.setDir("gmt_modified");
        queryListRequest.setAsc(Boolean.FALSE);
        Result<List<ScItemManageRange>> listResult = scItemManageRangeService.queryList(queryListRequest);
        List<ScItemManageRangeSDO> scItemManageRangeSDOS = Lists.newArrayList();
        if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())){
            scItemManageRangeSDOS = listResult.getResult().stream().map(scItemManageRange -> convert(scItemManageRange))
                    .collect(Collectors.toList());
        }
        return Result.listSuccess(scItemManageRangeSDOS,listResult == null ? 0: listResult.getTotal());
    }

    /**
     * 获取货品经营范围
     * @param scItemManageRangeSearchRequest
     * @return
     */
    @Override
    public Result<List<ScItemManageRange>> search(ScItemManageRangeSearchRequest scItemManageRangeSearchRequest) {
        ScItemManageRangeLoadListRequest request = new ScItemManageRangeLoadListRequest();
        if (StringUtils.isNotBlank(scItemManageRangeSearchRequest.getSaleOrgId())){
            request.setSaleOrgId(scItemManageRangeSearchRequest.getSaleOrgId());
        }
        if (StringUtils.isNotBlank(scItemManageRangeSearchRequest.getBizUnitId())){
            request.setBizUnitId(scItemManageRangeSearchRequest.getBizUnitId());
        }
        request.setLimit(MAX_PAGE_SIZE);
        Result<List<ScItemManageRange>> listResult = scItemManageRangeService.loadList(request);
        int total = Optional.ofNullable(listResult).map(Result::getTotal).orElse(0);
        //分页获取全部
        if (total > MAX_PAGE_SIZE){
            List<ScItemManageRange> scItemManageRanges = Lists.newArrayList();
            scItemManageRanges.addAll(listResult.getResult());
            Integer totalPage = PageUtils.getTotalPage(total, MAX_PAGE_SIZE);
            //从第二页开始查
            for (Integer i = 1; i < totalPage; i++) {
                request.setStart(i * MAX_PAGE_SIZE );
                listResult = scItemManageRangeService.loadList(request);
                if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())){
                    scItemManageRanges.addAll(listResult.getResult());
                }
            }
            return Result.success(scItemManageRanges);
        }else {
            return listResult;
        }
    }

    /**
     *  获取货品范围带当前登录人权限
     */
    @Override
    @FacadeInvoker
    public Result<List<ScItemManageRange>> searchWithPermission() {
        EmployeeGetCurrentLoginResponse currentLoginResponse = bcOrderService.employeeGetCurrentLogin();
        if (currentLoginResponse == null || StringUtils.isBlank(currentLoginResponse.getRelatedOrganizationId())
            || StringUtils.isBlank(currentLoginResponse.getRelatedOrganizationType())){
            log.error("ScItemManageRangeReadServiceImpl_searchWithPermission_error");
            return Result.success(Lists.newArrayList());
        }
        Integer relatedOrganizationType = Integer.parseInt(currentLoginResponse.getRelatedOrganizationType());
        String relatedOrganizationId = currentLoginResponse.getRelatedOrganizationId();
        ScItemManageRangeSearchRequest scItemManageRangeSearchRequest = new ScItemManageRangeSearchRequest();
        if (relatedOrganizationType < OrganizationTypeEnum.COMPANY.getCode()){
            //分子公司阶层不限制
            return Result.success(Lists.newArrayList());
        }else if (relatedOrganizationType.equals(OrganizationTypeEnum.COMPANY.getCode())){
            scItemManageRangeSearchRequest.setBizUnitId(relatedOrganizationId);
        }else if (relatedOrganizationType.equals(OrganizationTypeEnum.SALES_ORGANIZATION.getCode())){
            scItemManageRangeSearchRequest.setSaleOrgId(relatedOrganizationId);
        }else {
            //销售组织之下的限制到销售组织层级
            GetTopOrganizationListRequest getTopOrganizationListRequest = new GetTopOrganizationListRequest();
            getTopOrganizationListRequest.setType(OrganizationTypeEnum.SALES_ORGANIZATION.getCode());
            getTopOrganizationListRequest.setId(relatedOrganizationId);
            Result<List<com.epoch.app.crplatformenhance.model.dto.TopOrganizationListResponse>> topOrganizationList = crPlatformEnhanceService.getTopOrganizationList(getTopOrganizationListRequest);
            if (topOrganizationList != null && org.apache.commons.collections4.CollectionUtils.isNotEmpty(topOrganizationList.getResult())){
                String saleOrgId = topOrganizationList.getResult().stream().filter(org -> OrganizationTypeEnum.SALES_ORGANIZATION.getCode().equals(org.getType()))
                        .findFirst().map(com.epoch.app.crplatformenhance.model.dto.TopOrganizationListResponse::getId).orElse(null);
                scItemManageRangeSearchRequest.setSaleOrgId(saleOrgId);
            }else {
                return Result.success(Lists.newArrayList());
            }
        }
        return search(scItemManageRangeSearchRequest);
    }

    //获取渠道/部门的上级销售组织
    private TopOrganizationListResponse queryTopSaleOrg(String organizationId){
        if (StringUtils.isBlank(organizationId)){
            return null;
        }
        GetTopOrganizationListRequest getTopOrganizationListRequest = new GetTopOrganizationListRequest();
        getTopOrganizationListRequest.setId(organizationId);
        getTopOrganizationListRequest.setType(OrganizationTypeEnum.SALES_ORGANIZATION.getCode());
        Result<List<TopOrganizationListResponse>> topOrganizationList = crPlatformEnhanceService.getTopOrganizationList(getTopOrganizationListRequest);
        if (topOrganizationList != null && CollectionUtils.isNotEmpty(topOrganizationList.getResult())){
            return topOrganizationList.getResult().stream().filter(topOrganizationListResponse -> OrganizationTypeEnum.SALES_ORGANIZATION.getCode().equals(topOrganizationListResponse.getType()))
                    .findFirst().orElse(null);
        }
        return null;
    }

    //转换结果
    private ScItemManageRangeSDO convert(ScItemManageRange scItemManageRange){
        if (scItemManageRange == null){
            return null;
        }
        ScItemManageRangeSDO scItemManageRangeSDO = new ScItemManageRangeSDO();
        BeanUtils.copyProperties(scItemManageRange,scItemManageRangeSDO);

        StatusDesc statusDesc = new StatusDesc();
        //货品经营范围的状态
        if (ScItemManageRangeStatus.ENABLE.getValue().equals(scItemManageRange.getStatus())){
            statusDesc.setText("已启用");
            statusDesc.setValue(true);
            scItemManageRangeSDO.setStatusMeaning("已启用");
            scItemManageRangeSDO.setHideEnable(true);
            scItemManageRangeSDO.setHideDisabled(false);
        }else {
            statusDesc.setText("已禁用");
            statusDesc.setValue(false);
            scItemManageRangeSDO.setStatusMeaning("已禁用");
            scItemManageRangeSDO.setHideEnable(false);
            scItemManageRangeSDO.setHideDisabled(true);
        }
        scItemManageRangeSDO.setStatusDesc(statusDesc);
        //获取创建人名称
        scItemManageRangeSDO.setCreator(getRealName(scItemManageRange.getCreator()));
        scItemManageRangeSDO.setUpdater(getRealName(scItemManageRange.getUpdater()));
        return scItemManageRangeSDO;
    }

    //从创建人json中获取结果
    private String getRealName(String user){
        JSONObject creator = JSONObject.parseObject(user);
        if (creator != null){
            return creator.getString("realName");
        }
        return null;
    }
}
